package com.apes.fn.scm.retailOrder.service.retailProcess.process;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.contract.FnContract;
import com.apes.fn.scm.contract.FnContractRepository;
import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.fn.scm.retailOrder.service.retailProcess.CommonRetailDataProcess;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.Optional;

/**
 * 年审订单
 *
 * 控制逻辑：APP 需要传入 商品明细上面的供应商字段，并且年审单据的商品规则字段为 10(代销带安逻辑)
 *
 * @author wuq
 * @create 2021-05-21 17:00
 */
@Service
public class AnnualAuditRetailProcess extends CommonRetailDataProcess {

    @Override
    public void beforeSave(RetailOrder retailOrder) {
        // 获取年审价格的成本
        beforeProcess(retailOrder, this::getAnnualAuditProductCostPrice);
    }

    private void getAnnualAuditProductCostPrice(RetailOrder retailOrder) {

        retailOrder.getSaleItems().forEach(
                retailOrderItem -> {
                    // 设置 productRule, 年审默认的设置为 10
                    retailOrderItem.setProductRule(10);

                    PartyRole platformCompany = getPlatFormCompany(retailOrder.getCompany());
                    retailOrderItem.setPlatform(platformCompany);
                    retailOrderItem.setOriginSupplier(retailOrderItem.getSupplier());   // 设置原始供应商

                    // 查询城市
                    Store store = SpringManager.getBean(StoreRepository.class).findByDept(retailOrder.getDept());
                    Optional.ofNullable(store).orElseThrow( ()-> new RuntimeException("根据部门信息，未找到门店信息，请检查！") );

                    // 取平台的条件策略
                    Map strategyParam = MapUtil.mapper("conditionStrategyId", "CG01", "PRODUCT_ID", retailOrderItem.getProduct().getId(),
                            "CLASSIFY_ID", retailOrderItem.getProduct().getClassify().getId(),
                            "SYS_RQ", new Date(), "SUPPLIER_ID", retailOrderItem.getSupplier().getId(), "COMPANY_ID", platformCompany.getId(),
                            "CITY", store.getCity().getId());
                    Object obj = invoke("condition.execConditionStrategy", strategyParam);
                    JSONObject result = new JSONObject(MapUtil.mapped(obj));

                    if (result.getDouble("P001") == 0) {
                        throw new RuntimeException("年审订单无成本，请联系相关人员定义，商品名称：" + retailOrderItem.getProduct().getName());
                    }

                    // 内部交易的价格，暂时统一一个价格
                    retailOrderItem.setInnerSalePriceUnit(result.getDouble("P001"));
                    retailOrderItem.setPriceOutUnitInTax(result.getDouble("P001"));

                    // 直营模式、直营子公司 计算票点逻辑
                    String operationId = retailOrder.getCompany().getParty().getCorporate().getOperation().getId();
                    if (LogicalUtil.in(operationId, "001661", "001072") ) {
                        if (result.getDouble("P101") == null) throw new RuntimeException("直营模式下，条件策略票点未定义！");
                        // 和供应商结算的价格需要修改
                        retailOrderItem.setInnerSalePriceUnit(result.getDouble("P001") * ( 1 + result.getDouble("P101" )/ 100) );

                        // 直营子公司，由于 车宝需要对外部供应商增加票点，所以外部结算价也需要增加票点
                        if ("001661".equals(operationId)) {
                            retailOrderItem.setPriceOutUnitInTax(result.getDouble("P001") * ( 1 + result.getDouble("P101" )/ 100) );
                        }
                    }

                    if ("1007".equals(platformCompany.getId())) {
                        retailOrderItem.setReferTax(retailOrderItem.getPriceOutUnitInTax() * 1.05);       // 赋值参考成本
                    }
                });
    }

    private PartyRole getPlatFormCompany(PartyRole partyRole) {
        ArrayList rows = new ArrayList();
        rows.add(MapUtil.mapper("field", "state", "operator", "EQ", "value", "approve"));
        rows.add(MapUtil.mapper("field", "validPeriod", "operator", "GT", "value", new Date()));
        rows.add(MapUtil.mapper("field", "partner.id", "operator", "EQ", "value", partyRole.getId()));
        FnContract contract = SpringManager.getBean(FnContractRepository.class).findAll(JpaDsl.toCriteria(rows)).stream().findFirst().orElse(null);
        if (contract == null) {
            // 2022-01-05 按照老胡要求，取不到值的情况下，就默认 1001，后期业务出现错误数据，调整不管
            return SpringManager.getBean(PartyRoleRepository.class).findOne("1001");
        }
        return contract.getCompany();
    }

    @Override
    public void afterSave(RetailOrder retailOrder) {
        // 现在走零售有单退货
//        if (retailOrder.getAmtTotal() < 0) {
//            invoke("retail.coupon.returnVoucher", MapUtil.mapped(retailOrder));
//        }
    }

    @Override
    public boolean support(String orderType) {
        return "annualAudit".equals(orderType);
    }

}
